package com.example.computer_exam_training_sys.controller;

import com.example.computer_exam_training_sys.entity.User_Schedules_Entity;
import com.example.computer_exam_training_sys.service.User_Schedules_Service;
import com.example.computer_exam_training_sys.vo.NearestScheduleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.time.LocalDate;


@RestController
@RequestMapping("/schedules")
@CrossOrigin
public class User_Schedules_Controller {
    @Autowired
    private User_Schedules_Service service;

    // 查询所有
    @GetMapping("/all")
    public List<User_Schedules_Entity> getAll() {
        return service.selectAll();
    }

    // 按userId条件查询
    @GetMapping("/findbyid/{userId}")
    public List<User_Schedules_Entity> getByUserId(@PathVariable Integer userId) {
        return service.selectByUserId(userId);
    }

    // 新增
    @PostMapping("/add")
    public int add(@RequestBody User_Schedules_Entity entity) {
        return service.insert(entity);
    }

    // 更新
    @PutMapping("/update")
    public int update(@RequestBody User_Schedules_Entity entity) {
        return service.update(entity);
    }

    // 删除
    @DeleteMapping("/delete/{scheduleId}")
    public int delete(@PathVariable Integer scheduleId) {
        return service.delete(scheduleId);
    }

    // 查询最近日程（返回最近日程及距离现实时间天数）
    @GetMapping("/nearest/{userId}")
    public NearestScheduleVO getNearestSchedule(@PathVariable Integer userId) {
        List<User_Schedules_Entity> schedules = service.selectByUserId(userId);
        if (schedules == null || schedules.isEmpty()) return null;
        User_Schedules_Entity nearest = null;
        long minDays = Long.MAX_VALUE;
        LocalDate today = LocalDate.now();
        for (User_Schedules_Entity s : schedules) {
            long days = Math.abs(s.getScheduleDate().toEpochDay() - today.toEpochDay());
            if (days < minDays || (days == minDays && s.getScheduleDate().isAfter(nearest.getScheduleDate()))) {
                minDays = days;
                nearest = s;
            }
        }
        NearestScheduleVO vo = new NearestScheduleVO();
        vo.setSchedule(nearest);
        vo.setDaysToNow(minDays);
        return vo;
    }
}
